/*

*/
#ifndef SSD1306_H
#define SSD1306_H

#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"

#include "component_ultrasonic.h"
#include "component_dht11.h"

// 0X3C+SA0 - 0x3C or 0x3D
#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiAvrI2c oled;

float previous_temperature, previous_humidity;
String result_dht11_t, result_dht11_h;
String result_distance;

long previousMillis_display;
const int interval_display =2000;

void setup_ssd1306() {

#if RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS, RST_PIN);
#else   // RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
#endif  // RST_PIN >= 0
  // Call oled.setI2cClock(frequency) to change from the default frequency.

  oled.setFont(Adafruit5x7);

  uint32_t m = micros();
  oled.clear();
  oled.println();
  oled.set2X();
  oled.println("  MiniCar");
  delay(1000);

  dht11_on();

  result_dht11_t = "  T=" + String(temperature, 1) + "C";
  result_dht11_h = "  H=" + String(humidity, 1) + "%";
  previous_temperature = temperature;
  previous_humidity = humidity;
  oled.clear();
  oled.set2X();
  oled.println(result_dht11_t);
  oled.println(result_dht11_h);
  double *distances = HCSR04.measureDistanceCm();  // read distance
  distance = distances[0];
  result_distance = " D=" + String(distance, 1) + "cm";
  oled.println();
  oled.println(result_distance);
}

void loop_ssd1306() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis_display >= interval_display) {
    previousMillis_display = currentMillis;
    dht11_on();
    if (temperature != previous_temperature) {
      previous_temperature = previous_temperature;
      previous_humidity = humidity;
      result_dht11_t = "  T=" + String(temperature, 1) + "C";
      result_dht11_h = "  H=" + String(humidity, 1) + "%";
      //oled.clear();
      oled.println(result_dht11_t);
      oled.println(result_dht11_h);
      oled.println();
    };
  };
  result_distance = " D=" + String(distance, 1) + "cm";
  oled.println(result_distance);
}

#endif /* SSD1306_H */